//
//  DYDownloadVersion.m
//  DYFTManager
//
//  Created by 吴新庭 on 2019/5/16.
//

#import "DYDownloadVersion.h"

static NSString * kVersionInfoName = @"download-version.dat";
@implementation DYDownloadVersionItem

@end

@interface DYDownloadVersion ()

@property (nonatomic, copy) NSMutableArray<DYDownloadVersionItem *> *mItems;

@end

@implementation DYDownloadVersion

+ (DYDownloadVersion *)version {
    static DYDownloadVersion *inst = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSData *data = [NSData dataWithContentsOfFile:[self dataPath]];
        inst = [DYDownloadVersion yy_modelWithJSON:data];
        if (!inst) {
            inst = [[DYDownloadVersion alloc] init];
        }
    });
    
    return inst;
}

+ (NSArray<NSString *> *)modelPropertyBlacklist {
    return @[@"mItems"];
}

+ (NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass {
    return @{
             @"items": DYDownloadVersionItem.class
             };
}

- (NSMutableArray<DYDownloadVersionItem *> *)mItems {
    if (!_mItems) {
        _mItems = [NSMutableArray arrayWithArray:_items];
    }
    return _mItems;
}

- (NSArray<DYDownloadVersionItem *> *)items {
    return self.mItems;
}

- (DYDownloadVersionItem *)itemForKey:(NSString *)key {
    for (DYDownloadVersionItem *i in self.items) {
        if ([i.key isEqualToString:key]) {
            return i;
        }
    }
    
    DYDownloadVersionItem *item = [[DYDownloadVersionItem alloc] init];
    item.key = key;
    item.version = @"-1";
    [self.mItems addObject:item];
    return item;
}

- (void)save {
    [[self yy_modelToJSONData] writeToFile:[self.class dataPath] atomically:YES];
}

#pragma mark - Private
+ (NSString *)dataPath {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:kVersionInfoName];
    return path;
}

@end
